﻿Public Class Planilla_Ingreso

    Enum estado
        insertar
        modificar
    End Enum
    Enum termino
        aprobado
        rechazado
    End Enum

    Dim accion As estado = estado.insertar
    Dim acceso As New acceso_a_datos
    Dim idselected As Integer
    Dim combo_Turno_ As New combo
    Dim codigo_Egreso As Integer
    Dim primera_busqueda As Boolean = False

    'Detectar si se colocaron numeros en los campos correspondientes
    Private Sub txt_numDoc_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txt_Monto.KeyPress, txt_numero.KeyPress
        Select Case Asc(e.KeyChar)
            Case 4, 24, 4, 19, 127, 13, 9, 15, 14, 8, 46
                Exit Sub
        End Select

        If IsNumeric(e.KeyChar) = False Then
            e.KeyChar = ""
        End If
    End Sub

    Private Sub Planilla_Ingreso_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        acceso._tabla = "Turno"

        combo_Turno_.cargar(Me.cmb_turno, Me.acceso.leo_tabla("cod_Turno", "nombre"))
        Me.deshabilitar_Campos()
        Me.carga_grilla()

    End Sub

    'BOTON NUEVO
    Private Sub btn_nuevo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_nuevo.Click
        Me.habilitar_Campos()
        'Me.mask_fecha.Focus()
        Me.limpiar_campos()
        accion = estado.insertar
        Me.primera_busqueda = False
        txt_numero.Focus()
        lbl_monto_obligatorio.Visible = False
        lbl_orden_obligatorio.Visible = False
    End Sub

    'BOTON GUARDAR
    Private Sub btn_guardar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_guardar.Click

        If Me.validardatos(sender, e) = True Then
            If accion = estado.insertar Then
                If Me.validar_existencia() = termino.aprobado Then
                    If insertar_Ingreso() = termino.aprobado Then

                        MessageBox.Show("Exito al Grabar en Base de Datos", "Éxito", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
                        limpiar_campos()
                        deshabilitar_Campos()
                        btn_guardar.Enabled = False
                        carga_grilla()
                        Me.primera_busqueda = False

                    End If
                Else
                    MessageBox.Show("Ya esta cargado ese Número de Orden o Turno", "Importante", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    Exit Sub
                End If
            Else
                If Me.validardatos(sender, e) = True And accion = estado.modificar Then
                    If modificar_Ingreso() = termino.aprobado Then
                        MessageBox.Show("Exito al Grabar en Base de Datos", "Éxito", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
                        limpiar_campos()
                        deshabilitar_Campos()
                        btn_guardar.Enabled = False
                        carga_grilla()
                        Me.primera_busqueda = False
                    End If
                End If
            End If
        End If
    End Sub

    'BOTON VOLVER
    Private Sub btn_volver_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_volver.Click
        Me.Close()
        Encargado.Show()
    End Sub

    'BOTON ELIMINAR
    Private Sub btn_eliminar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_eliminar.Click

        If txt_numero.Text = "" Then
            MsgBox("Debe seleccionar un Ingreso antes de eliminar", MsgBoxStyle.Exclamation, "Atencion")
            Exit Sub
        End If
        If MsgBox("¿Realmente desea eliminar?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Importante") = MsgBoxResult.No Then
            Exit Sub
        End If

        Me.eliminar()
        Me.carga_grilla()
        Me.limpiar_campos()

        Me.btn_eliminar.Enabled = False
        Me.btn_buscar.Enabled = True
        Me.btn_guardar.Enabled = False

    End Sub

    'Validamos la existencia en la Base de Datos
    Private Function validar_existencia() As termino

        Dim consulta As String = ""
        Dim tabla As New Data.DataTable

        'se tiene en cuenta el numero de orden y el año
        'ya que para años distintos de puede tener un mismo numero de orden
        consulta = "SELECT * FROM Ingreso "
        consulta &= "WHERE ((numero_Orden=" & Me.txt_numero.Text
        consulta &= " AND YEAR(fecha)='" & Me.time_fecha.Text.Substring(6) & "')"
        consulta &= " OR (fecha='" & Me.time_fecha.Text & "'"
        consulta &= " AND cod_Turno=" & Me.cmb_turno.SelectedValue & "))"

        tabla = acceso._consulta(consulta)

        'Vemos si hay algo en las FILAS
        If tabla.Rows.Count() = 1 Then
            Return termino.rechazado
        Else
            Return termino.aprobado
        End If

    End Function

    'VALIDACION DE DATOS
    Private Function validardatos(ByVal sender As System.Object, ByVal e As System.EventArgs) As Boolean

        'If Me.mask_fecha.Text = "" Then
        '    MessageBox.Show("Debe completar el campo Fecha", "IMPORTANTE", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
        '    Me.mask_fecha.Focus()
        '    Return False
        '    Exit Function
        'End If

        If Me.txt_numero.Text = "" Then
            'MessageBox.Show("Debe completar el Codigo de la Planilla", "IMPORTANTE", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
            indicar_obligatorios(sender, e)
            Me.txt_numero.Focus()
            Return False
            Exit Function
        End If

        If Me.cmb_turno.SelectedIndex = -1 Then
            MessageBox.Show("Debe seleccionar un turno", "IMPORTANTE", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
            Me.cmb_turno.Focus()
            Return False
            Exit Function
        End If

        If Me.txt_Monto.Text = "" Then
            'MessageBox.Show("Debe completar el campo Monto", "IMPORTANTE", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
            indicar_obligatorios(sender, e)
            Me.txt_Monto.Focus()
            Return False
            Exit Function
        End If

        Return True

    End Function

    Private Sub deshabilitar_Campos()

        'campos
        Me.time_fecha.Enabled = False
        Me.txt_numero.Enabled = False
        Me.cmb_turno.Enabled = False
        Me.txt_Monto.Enabled = False
        Me.cmb_turno.SelectedIndex = -1

        'botones
        Me.btn_buscar.Enabled = True
        Me.btn_eliminar.Enabled = False
        Me.btn_guardar.Enabled = False

    End Sub

    Private Sub habilitar_Campos()

        'campos
        Me.time_fecha.Enabled = True
        Me.txt_numero.Enabled = True
        Me.cmb_turno.Enabled = True
        Me.txt_Monto.Enabled = True

        'botones
        Me.btn_buscar.Enabled = True
        Me.btn_eliminar.Enabled = False
        Me.btn_guardar.Enabled = True
    End Sub

    Private Sub limpiar_campos()

        'limpio campos en genral
        Me.time_fecha.Text = ""
        Me.txt_numero.Text = ""
        Me.cmb_turno.SelectedIndex = -1
        Me.txt_Monto.Text = ""

    End Sub

    'CARGAMOS GRILLA
    Private Sub carga_grilla()
        acceso._tabla = "Ingreso"
        Dim tabla As New Data.DataTable
        Dim txt_sql As String = ""
        Dim c As Integer = 0

        'metodo para insertar en la tabla ingreso.. referente a la planilla de Ingreso..
        txt_sql = "SELECT I.fecha, I.numero_Orden,  T.nombre as nom, I.monto_Recaudado"
        txt_sql += " FROM Ingreso I INNER JOIN Turno T ON I.cod_turno = T.cod_Turno"

        'guardo los datos de la consulta en la tabla
        tabla = acceso._consulta(txt_sql)

        Me.grilla_Ingreso.Rows.Clear()

        For c = 0 To tabla.Rows.Count - 1
            Me.grilla_Ingreso.Rows.Add(FormatDateTime(tabla.Rows(c)("fecha"), DateFormat.ShortDate), tabla.Rows(c)("numero_Orden"), tabla.Rows(c)("nom"), tabla.Rows(c)("monto_Recaudado"))
        Next

    End Sub

    'GRABAMOS, INSERTAMOS
    Private Function insertar_Ingreso() As termino
        acceso._tabla = "Ingreso"
        Dim consulta As String = ""

        consulta = "numero_Orden=" & Me.txt_numero.Text
        consulta += ", fecha=" & Me.time_fecha.Text
        consulta += ", cod_Turno=" & Me.cmb_turno.SelectedValue
        consulta += ", monto_Recaudado=" & Me.txt_Monto.Text

        acceso._insertar(consulta)
        Me.deshabilitar_Campos()

        Return termino.aprobado
    End Function

    'MODIFICACION DE DATOS
    Private Function modificar_Ingreso() As termino

        If validar_existencia() = termino.aprobado Then
            'actualizamos datos tabla Egreso
            acceso._tabla = "Ingreso"
            Dim consulta As String = ""
            Dim valores As String = ""
            Dim restriccion As String = ""


            valores = "cod_Turno=" & Me.cmb_turno.SelectedValue
            valores &= ", monto_Recaudado =" & Me.txt_Monto.Text

            restriccion = "numero_Orden =" & Me.txt_numero.Text
            restriccion &= ", fecha=" & Me.time_fecha.Text

            Try
                acceso._modificar(valores, restriccion)
                Return termino.aprobado
            Catch ex As Exception
                MessageBox.Show("Error al Modificar Planilla de Ingresos en la base de datos" & vbCrLf + vbCrLf & "Mensaje de error: " & vbCrLf + ex.Message, "Error al Insertar en la base de datos", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
                Return termino.rechazado
                Exit Function
            End Try
        Else
            MessageBox.Show("Ya esta cargado ese Turno para esa Fecha", "Importante", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return termino.rechazado
        End If
    End Function

    'ELIMINAR INGRESO
    Private Function eliminar() As termino
        Dim comando As String = ""

        comando = "DELETE FROM Ingreso "
        comando += "WHERE (numero_Orden=" & Me.txt_numero.Text
        comando += " AND fecha='" & Me.time_fecha.Text & "')"

        Try
            acceso._borrar(comando)
            Return termino.aprobado
        Catch ex As Exception
            MessageBox.Show("Error al Eliminar la Planilla de Ingreso en la base de datos" & vbCrLf + vbCrLf & "Mensaje de error: " & vbCrLf + ex.Message, "Error al Insertar en la base de datos", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
            Return termino.rechazado
            Exit Function
        End Try
    End Function

    'GRILLA
    Private Sub grilla_Ingreso_CellContentDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grilla_Ingreso.CellContentDoubleClick

        Dim nro_Orden As Integer = Me.grilla_Ingreso.CurrentRow.Cells("Numero").Value
        Dim fecha_Ingreso As String = Me.grilla_Ingreso.CurrentRow.Cells("Fecha").Value
        Dim tabla As New Data.DataTable
        Dim consulta As String = ""

        consulta = "SELECT * FROM Ingreso "
        consulta += "WHERE numero_Orden=" & nro_Orden & " AND fecha='" & fecha_Ingreso & "'"

        tabla = acceso._consulta(consulta)

        Me.habilitar_Campos()
        Me.txt_numero.Enabled = False
        Me.btn_eliminar.Enabled = True
        Me.time_fecha.Enabled = False
        Me.time_fecha.Enabled = False

        Me.txt_numero.Text = nro_Orden
        Me.time_fecha.Text = fecha_Ingreso
        Me.cmb_turno.SelectedValue = tabla.Rows(0)("cod_Turno")
        Me.txt_Monto.Text = tabla.Rows(0)("monto_Recaudado")

        accion = estado.modificar
    End Sub


    Private Sub btn_buscar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_buscar.Click
        Busqueda_Ingreso.Show()

    End Sub

    Private Sub Planilla_Ingreso_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
        Dispose()
    End Sub

    Private Sub txt_numero_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txt_numero.Leave
        If txt_numero.Text = "" And btn_volver.Focused = False Then
            lbl_orden_obligatorio.Visible = True
        Else
            lbl_orden_obligatorio.Visible = False
        End If
    End Sub

    Private Sub txt_Monto_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txt_Monto.Leave
        If txt_Monto.Text = "" And btn_volver.Focused = False Then
            lbl_monto_obligatorio.Visible = True
        Else
            lbl_monto_obligatorio.Visible = False
        End If
    End Sub

    Public Sub indicar_obligatorios(ByVal sender As System.Object, ByVal e As System.EventArgs)
        txt_numero_Leave(sender, e)
        txt_Monto_Leave(sender, e)
        
    End Sub
End Class